<?php
require_once 'seedniaenvs.php';
include 'log4php/Logger.php';
require 'Slim/Slim.php';
require 'restutil.php';

require_once APPROOT.'/application/classes/util/session.php';
require_once APPROOT.'/application/classes/util/datetime.php';
require_once APPROOT.'/application/classes/rest/client.php';
require_once APPROOT.'/application/classes/rest/response.php';
require_once APPROOT.'/application/classes/service/RestServiceStubBase.php';
require_once APPROOT.'/application/classes/service/GenericSeedniaServiceStub.php';
require_once APPROOT.'/application/classes/service/PostServiceStub.php';

Logger::configure('log4php.xml');

$app = new Slim(array(
    'log.enable' => true,
    'log.path' => './logs',
    'log.level' => 3,
));

//GET route
$app->get('/post/:sid', 'getPost') ;
$app->post('/post', 'postPost') ;
$app->put('/post/:sid', 'putPost') ;
$app->delete('/post/:sid', 'deletePost') ;
$app->get('/project/post/:projectSid', 'getPostsOfProject') ;

$app->get('/comment/:sid', 'getComment') ;
$app->post('/comment', 'postComment') ;
$app->put('/comment/:sid', 'putComment') ;
$app->delete('/comment/:sid', 'deleteComment') ;

$app->run();


function getPostService()
{
	$postService = new Service_PostServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_POST.'/', ACCESS_TOKEN);
	return $postService;
}

function getPost($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getPost(".$sid.")");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	$postService = getPostService();
	
	$post = $postService->getByXid($sid);
	
    $result = json_encode($post);
    echo $result;
};

function postPost() {
    $logger = Logger::getLogger("seednia");
    $logger->info("at postPost()");

	try {
		$request = Slim::getInstance()->request();
		$body = $request->getBody();
		$record = json_decode($body, true);

		normalizeRecord($record);
		
		$userInfo = Util_Session::getUserInfo();
		$record['creatorSid'] = $userInfo['userSid'];
		
		$postService = getPostService();
		$sid = $postService->add($record);
		$record['sid'] = $sid;
		echo json_encode($record);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function putPost($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at putPost(".$sid.")");
	
	try {
		$request = RestUtil::getRequest();
		
		$body = $request->getBody();
		$record = json_decode($body, true);
		$record['sid'] = $sid;

		normalizeRecord($record);
		
		if ($record['status'] == STATUS_COMPLETED) {
			$record['actualDate'] = Util_Datetime::format_std(new DateTime);
		}

		$postService = getPostService();
		$result = $postService->update($record);
		echo json_encode($record);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function deletePost($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at deletePost(".$sid.")");

	try {
		$postService = getPostService();
		$postService->deleteByXid($sid);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function getPostsOfProject($projectSid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getPostsOfProject");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	$postService = getPostService();
	
	$postCriteria = array('_retrieveScope'=> 2);
	$postCriteria['projectSid'] = $projectSid;
	$posts = $postService->getPostList($postCriteria, 0, 15);
	
    //$result = '{"post": ' . json_encode($posts) . '}';
	$result = json_encode($posts);
    echo $result;
};

////////// Comments //////////


function getCommentService()
{
	$commentService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_COMMENT.'/', ACCESS_TOKEN);
	return $commentService;
}

function getComment($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getComment(".$sid.")");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	$postService = getCommentService();
	
	$post = $postService->getByXid($sid);
	
    $result = json_encode($post);
    echo $result;
};

function postComment() {
    $logger = Logger::getLogger("seednia");
    $logger->info("at postComment()");

	try {
		$request = Slim::getInstance()->request();
		$body = $request->getBody();
		$record = json_decode($body, true);

		normalizeRecord($record);
				
		$userInfo = Util_Session::getUserInfo();
		$record['creatorSid'] = $userInfo['userSid'];
		$record['targetType'] = "Post";
		
		$sid = getCommentService()->add($record);
		$record['sid'] = $sid;
		echo json_encode($record);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function putComment($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at putComment(".$sid.")");
	
	try {
		$request = RestUtil::getRequest();
		
		$body = $request->getBody();
		$record = json_decode($body, true);
		$record['sid'] = $sid;

		normalizeRecord($record);

		$result = getCommentService()->update($record);
		echo json_encode($record);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function deleteComment($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at deletePost(".$sid.")");

	try {
		$commentService = getCommentService();
		$commentService->deleteByXid($sid);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function normalizeRecord(&$record)
{
	if (array_key_exists('projectName', $record))
		unset($record['projectName']);
	if (array_key_exists('projectId', $record))
		unset($record['projectId']);
	if (array_key_exists('creatorId', $record))
		unset($record['creatorId']);

	//yyyy-MM-dd'T'HH:mm:ss.SZ
	if (!array_key_exists('createDt', $record))
		$record['createDt'] = Util_Datetime::format_std(new DateTime);
	else 
		$record['createDt'] = substr($record['createDt'], 0, 19);

	if (!array_key_exists('lastModifiedDt', $record))
		$record['lastModifiedDt'] = Util_Datetime::format_std(new DateTime);
	else 
		$record['lastModifiedDt'] = substr($record['lastModifiedDt'], 0, 19);

	return $record;
}

function getCommentsOfPost($postSid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getPostsOfProject");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	$commentService = getCommentService();
	
	$criteria = array('targetType'=>'Post');
	$criteria['targetSid'] = $postSid;
	$posts = $commentService->get($criteria, 0, 15);
	
    //$result = '{"post": ' . json_encode($posts) . '}';
	$result = json_encode($posts);
    echo $result;
};

////////// TESTS //////////

function getPostTest($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getPost");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	
	$post = new stdClass();
	$post->creatorDto = new stdClass();
	$post->creatorDto->sid = 1;
	$post->creatorDto->displayName = "Young Suk";
	$post->creatorSid = 1;
	$post->subject = "My Test";
	$post->body = "Hello World";
	
    $result = json_encode($post);
    echo $result;
};

function getPostsOfProjectTest($projectSid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getPost");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	$result = <<<EOT
[{ "sid": 1, "body": "FROM REST nice test", "creatorDisplayName": "REST Ahn", "createDt": "2012/1/3", "creatorProfileImageSid": 58, "projectSid": 11, "projectName":"Seednia" },
	{ "sid": 2, "body": "FROM REST 22", "creatorDisplayName": "REST 2", "createDt": "2012/1/3", "creatorProfileImageSid": 58, "projectSid": 11, "projectName":"Seednia" }]
EOT;
	echo $result;
};